package colopl.http.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.*;

public class RegexUtil {

    private List<String> regexs = new ArrayList<String>();

    private List<List<String>> results = new ArrayList<List<String>>();

    public void addRegex(String regex, List<String> result) {
        regexs.add(regex);
        results.add(result);
    }

    public void parse(InputStream is, String encode) throws IOException {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(is, encode));
            String line = null;
            while ((line = br.readLine()) != null) {
                for (int i = 0; i < regexs.size(); i++) {
                    List<String> result = results.get(i);
                    List<String> tmp = extractAll(regexs.get(i), line);
                    if (tmp != null) {
                        result.addAll(tmp);
                    }
                }
            }
        } finally {
            try {
                br.close();
                is.close();
            } catch (IOException e) {
                // TODO warn
                throw e;
            }
        }
    }

    public void parse(InputStream is) throws IOException {
        this.parse(is, "UTF-8");
    }

    public static String extract(String regex, String target) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(target);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }
    
    public static List<String> extractAll(String regex, String target) {
        List<String> list = new ArrayList<String>();;
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(target);
        while (matcher.find()) {
            list.add(matcher.group(1));
        }
        
        return list;
    }

}